<template>
  <div v-loading="pageLoading" element-loading-text="加载中...">
    <el-form :model="goodsForm" label-width="100px" ref="goodsFormDom">
      <el-form-item label="编码" prop="code">
        <el-input v-model="goodsForm.code"></el-input>
      </el-form-item>
  
      <el-form-item label="名称" prop="name">
        <el-input v-model="goodsForm.name"></el-input>
      </el-form-item>
  
      <el-form-item label="数量" prop="quantity">
        <el-input-number v-model="goodsForm.quantity" :min="1"></el-input-number>
      </el-form-item>
  
      <el-form-item label="类型" prop="type">
        <el-button-group>
          <el-button
            v-for="option in typeOptions"
            :key="option"
            :type="goodsForm.type === option ? 'primary' : 'default'"
            @click="goodsForm.type = option"
          >
            {{ option }}
          </el-button>
        </el-button-group>
      </el-form-item>
  
      <el-form-item label="进货价" prop="purchasePrice">
        <el-input-number v-model="goodsForm.purchasePrice" :min="0" :step="0.01" style="width: 240px"></el-input-number>
      </el-form-item>
  
      <el-form-item label="零售价" prop="salePrice">
        <el-input-number v-model="goodsForm.salePrice" :min="0" :step="0.01" style="width: 240px"></el-input-number>
      </el-form-item>
  
      <el-form-item label="经销商" prop="dealer">
        <el-select 
          v-model="goodsForm.dealer" 
          placeholder="请选择经销商" 
          style="width: 240px"
          :loading="isLoading"
          v-if="!isLoading"
        >
          <el-option 
            v-for="dealer in dealers" 
            :key="dealer.id" 
            :label="dealer.name" 
            :value="dealer.name"
          />
        </el-select>
      </el-form-item>
  
      <el-form-item>
        <el-button type="primary" @click="submitForm('goodsForm')">提交</el-button>
        <el-button @click="resetForm('goodsForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
  
<script setup>
import { ref, reactive, onMounted } from 'vue';
import { goodsTypes } from '@/cfg/config.js';  // 从配置文件中引入类型选项
import DealerService from '@/api/dealerService'; // 引入经销商服务
import GoodsService from '@/api/goodsService';
import { ElMessage } from 'element-plus';

// 定义 localStorage key
const STORAGE_KEY = 'goodsInventoryForm';

const pageLoading = ref(true); // 添加页面级别的 loading
const isLoading = ref(true); // Select 组件的 loading

// 从 localStorage 获取保存的表单数据
const getSavedFormData = () => {
  const savedData = localStorage.getItem(STORAGE_KEY);
  if (savedData) {
    return JSON.parse(savedData);
  }
  return null;
};

const goodsForm = reactive({
  code: '',
  name: '',
  quantity: 1,
  type: '文具',  // 设置默认类型为"文具"
  dealer: '',
  purchasePrice: 0, // 新增进货价字段
  salePrice: 0, // 新增零售价字段
});

const goodsFormDom = ref(null);
const typeOptions = ref(goodsTypes);
const dealers = ref([]);

onMounted(async () => {
  pageLoading.value = true;
  try {
    // 获取经销商列表
    await fetchDealers();
    
    // 加载保存的表单数据
    const savedData = getSavedFormData();
    if (savedData) {
      Object.assign(goodsForm, savedData);
    }
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error('页面初始化失败');
  } finally {
    pageLoading.value = false;
  }
});

async function fetchDealers() {
  isLoading.value = true;
  try {
    const response = await DealerService.getAllDealers('goods'); // 只获取文具经销商
    dealers.value = response.data;
  } catch (error) {
    console.error("获取经销商列表失败: ", error);
    ElMessage.error('获取经销商列表失败');
  } finally {
    isLoading.value = false;
  }
}

function submitForm() {
  if (goodsFormDom.value) {
    goodsFormDom.value.validate(async (valid) => {
      if (valid) {
        pageLoading.value = true;
        try {
          // 处理提交逻辑
          const formData = Object.assign({}, goodsForm);
          // 保存表单数据到 localStorage
          localStorage.setItem(STORAGE_KEY, JSON.stringify({
            name: formData.name,
            quantity: formData.quantity,
            purchasePrice: formData.purchasePrice,
            salePrice: formData.salePrice,
            type: formData.type,
            dealer: formData.dealer
          }));
          await addGoods(formData);
        } finally {
          pageLoading.value = false;
        }
      } else {
        console.log('表单验证失败');
        return false;
      }
    });
  }
}

function resetForm() {
  if (goodsFormDom.value) {
    goodsFormDom.value.resetFields();
    // 清除 localStorage 中的数据
    localStorage.removeItem(STORAGE_KEY);
  }
}

async function addGoods(goods) {
  try {
    const response = await GoodsService.addGoods(goods);
    ElMessage({
      message: '添加货物成功',
      type: 'success',
      duration: 3000
    });
    goodsForm.name = ''; // 添加成功后只清空名称字段
  } catch (error) {
    console.error("Error adding goods: ", error);
    ElMessage({
      message: error.response?.data?.message || '添加货物失败',
      type: 'error',
      duration: 3000
    });
  }
}
</script>
  
<style>
/* 样式部分保持不变 */
</style>
  